# -*- coding: utf-8 -*-

import sys
from pymongo import MongoClient
import json


def get_rank(user_id):
    client = MongoClient()
    db = client.shiyanlou
    contests = db.contests
    rank = 0
    score = 0
    submit_time = 0

    # \u8ba1\u7b97\u7528\u6237 user_id \u7684\u6392\u540d\u3001\u603b\u5206\u6570\u53ca\u82b1\u8d39\u7684\u603b\u65f6\u95f4

    result = contests.aggregate(
        [{'$group': {'_id': "$user_id", 'total': {'$sum': "$score"}, 'time': {'$sum': "$submit_time"}}},
         {'$sort': {"total": -1, "time": 1}},
         {'$project': {"user_id": "$_id", 'total': '$total', 'time': "$time"}}])
    for r in result:
        rank += 1;
        if (user_id == r["user_id"]):
            score = r["total"]
            submit_time = r["time"]
            break
    # \u4f9d\u6b21\u8fd4\u56de\u6392\u540d\uff0c\u5206\u6570\u548c\u65f6\u95f4\uff0c\u4e0d\u80fd\u4fee\u6539\u987a\u5e8f
    return rank, score, submit_time


if __name__ == '__main__':

    '''
    1. \u5224\u65ad\u53c2\u6570\u683c\u5f0f\u662f\u5426\u7b26\u5408\u8981\u6c42
    2. \u83b7\u53d6 user_id \u53c2\u6570
    '''
    l = sys.argv[1:]
    user_id = 0
    try:
        user_id = int(l[0])
    except BaseException:
        print("Parameter Error")
        exit()
    # \u6839\u636e\u7528\u6237 ID \u83b7\u53d6\u7528\u6237\u6392\u540d\uff0c\u5206\u6570\u548c\u65f6\u95f4
    userdata = get_rank(user_id)
    print(userdata)